<?php
/**
 * 绵阳妇幼中间件
 *
 *
 * @author wangwh
 */

namespace Myfuyou\Controller;

class MyfuyouControlController
{
    // SoapClient 对象
    private $soap = FALSE;

    // 记录是否为正式环境
    private $isFormal = FALSE;

    //是否开启缓存
    private static $CACHE = false;

    // 医疗机构科室列表缓存建
    private static $CACHE_INSTITUTION_CLASS_LIST = 'CACHE_INSTITUTION_CLASS_LIST';


    static $URL_API = 'http://220.166.60.252:8083/wxjk.dll/wsdl/Iwxjk';//http://192.168.203.55:8078/HisService.asmx?WSDL
    static $back_URL_API = "http://localhost:8081/";

    //医院id
    private $hospitalId;

    //自助机id
    private $userId;

    /**
     * 构造函数
     */
    function __construct()
    {
        $this->hospitalId = 75;
        if (!method_exists($this, ACTION_NAME)) {
            $function = ACTION_NAME;
            A('Receive')->$function();
        }
    }


    public $hospitalKey = array(
        "75" => "7daf7603429012aeae417fa9beed9c75",
    );
    //正式地址
    //	static $URL_API = "http://125.64.9.81:8088/rmc/mobile/web";
    //	static $version = "2.2.7";
    //	private $token = "6a2967e64a994e54b533aa7942328179";
    //正式地址


    // 	static $URL_API = "http://125.64.9.81:8088/rmc/mobile/web";
    /**
     * 请求His API
     *
     *   使用SoapClient请求HIS webservice接口
     *
     * @param String $Flag 类型
     * @param String $Content xml请求内容
     * @param String $Result_K 返回xml中的跟节点key
     *
     * @return array
     */


    private function soapGetDate($Flag, $Content)
    {
//        $this->isFormal = ($_SERVER['SERVER_NAME']!="localhost" && "histest.mobimedical.cn"!=$_SERVER['SERVER_NAME']);
        $this->isFormal = false;

        if (!$this->soap) {
            $this->soap = new \SoapClient(self::$URL_API, array("connection_timeout" => 15));
        }
        try {

            /* 正式环境 */
            if ($this->isFormal) {
                //专线接口,走平台
                try {
                    $result = $this->soap->Weixin($Content);
                } catch (\Exception $e) {
                    $fileContent = $Content . "\n" . $e->getMessage();
                    $dir = "soapGetDate/";
                    \Org\Util\File::createDir($dir);
                    file_put_contents($dir . $Flag . "_error.txt", $fileContent);
                    return array('ResultCode' => -1, "ErrorMsg" => "系统异常，请稍后重试21！");
                }
                $Result_K = "Weixin" . Result;

                /* 测试环境 */
            } else {
                $result = $this->soap->$Flag( $Content);
                /* 记录请求日志   */
                $fileContent = $Content . "\r" . var_export($result, true);
                $dir = "soapGetDate/" . date("Y-m-d") . "/" . $Flag . "/";
                $filename = date("H_i_s") . "_" . rand(10000, 99999);
                writeLog($dir, $filename, $fileContent);

                return json_decode(json_encode(json_decode(json_encode((array)simplexml_load_string(substr($result, 54)), true))), true);
            }


        } catch (\Exception $e) {
            /* 记录请求异常日志  */
            $fileContent = $Content . "\n" . $e->getMessage();
            $dir = "soapGetDate/" . date("Y-m-d") . "/" . $Flag . "/";
            $filename = date("H_i_s") . "_error";
            writeLog($dir, $filename, $fileContent);
            return array('ResultCode' => -1, "ErrorMsg" => "系统异常，请稍后重试22！");
            exit;
        }
    }


    function Post($url, $method, $post = null)
    {
        if (is_array($post)) {
            ksort($post);
            $content = http_build_query($post);
            $content_length = strlen($content);
            $options = array(
                'http' => array(
                    'method' => 'POST',
                    'header' =>
                        "Content-type: application/x-www-form-urlencoded; charset=utf-8\r\n" .
                        "Content-length: $content_length\r\n",
                    'content' => $content
                )
            );
            $res = file_get_contents($url, false, stream_context_create($options));
            $fileContent = var_export($post, true) . "\r" . var_export($res, true) . "\r" . var_export(json_decode($res, true), true);
            $dir = "soapGetDateXt/" . date("Y-m-d") . "/" . $method . "/";
            $filename = date("H_i_s") . "_" . rand(10000, 99999);
            writeLog($dir, $filename, $fileContent);
            return $res;
        }
    }

    /**
     * 中间件签名验证
     * @param array $params
     * @return string
     */
    function middelEnCodeSign($params)
    {
        ksort($params);
        $preString = "";
        $time = $params['time'];
        $hospitalId = $params['hospitalId'];
        foreach ($params as $k => $v) {
            if ($k == 'time' || $k == 'sign' || !$v)
                continue;
            $preString .= $k . "=" . $v;
        }

        $keyString = $this->hospitalKey[$hospitalId];
        //加密
        return sha1($preString . $keyString . $time);
    }


    /**
     * 确认病人信息  绑卡
     * @param $car_no '就诊卡号'
     * @param $user_name '病人姓名'
     */
    public function cardInfoQuery()
    {
//        $sign       = $this->middelEnCodeSign($_POST);
//        if($sign!=$_POST['sign']){
//            echo "签名不正确";exit;
//        }
        $card_no    = $_POST['identy_id'];
        $user_name  = $_POST['user_name'];

        //$card_no = '600143066';

        $Content ="<HIS><card_no>".$card_no."</card_no></HIS>";

        $searchKey = "patient";
        $result = $this->soapGetDate($searchKey, $Content);
        if ($result['status'] == 0 && !empty($result['data']['name'])) {
            if ($result['data']['name'] == $user_name && $result['status'] == 0) {
                $returnArr['status'] = 1;
                $returnArr['errorMsg'] = "绑卡成功";
                $returnArr['data'] = $result['Data'];
            } else {
                $returnArr['status'] = 2;
                $returnArr['errorMsg'] = "姓名输入有误";
                $returnArr['data'] = array();
            }

        } else {
            $returnArr['status'] = 2;
            $returnArr['errorMsg'] = $result['ResultMsg'];
            $returnArr['data'] = array();

        }

        echo json_encode($returnArr);
    }

    function objarray_to_array($obj)
    {
        $ret = array();
        foreach ($obj as $key => $value) {
            if (gettype($value) == "array" || gettype($value) == "object") {
                $ret[$key] = objarray_to_array($value);
            } else {
                $ret[$key] = $value;
            }
        }
        return $ret;
    }

    /**
     * 值班科室列表
     * @param $data '当天值班科室时间'
     * @param $period '上午或是下午'
     */
    public function dutyDept()
    {
//        $sign       = $this->middelEnCodeSign($_POST);
//        if($sign!=$_POST['sign']){
//            echo "签名不正确";exit;
//        }
        $date = $_POST['date'];
        $date = date('Y-m-d');
        $period = $_POST['period'];
        $period = 'pm';
        $Content = '<HIS><date>' . $date . '</date><period>' . $period . '</period></HIS>';
        $searchKey = "dutyDept";
        $result = $this->soapGetDate($searchKey, $Content);
        // dump($result);die();
        $data = array();
        if (count($result['data'][0]) == 0) {
            $result['data'][0] = $result['data'];
        }
        //>>将deptDutyId作为数组的索引

        // $redis = \Common\Model\ServeModel::serveRedis();
        foreach ($result['data'] as $k => $v) {
            // $key = 'dept' . $v['dept_id'];
            // $value = $redis->get($key);
            // if (!$value) {
            //     $redis->set($key, $v['title']);
            // }
            //没有排班医生的科室不显示
            $doctorCount = $this->DoctorCount($date, $period, $v['dept_id']);
            if ((int)$doctorCount['status'] == 0 && !empty($doctorCount['data'])) {
                $data[$v['dept_duty_id']]['deptDutyId'] = $v['dept_duty_id'];
                $data[$v['dept_duty_id']]['deptId'] = $v['dept_id'];
                $data[$v['dept_duty_id']]['title'] = $v['title'];
            }
        }


        if ($result['status'] == 0 && !empty($result['data'])) {
            $returnArr['status'] = 1;
            $returnArr['errorMsg'] = '';
            $returnArr['data'] = $data;
        } else {
            $returnArr['status'] = 2;
            $returnArr['errorMsg'] = $result['error_msg'];
            $returnArr['data'] = array();
        }
        echo json_encode($returnArr);

    }

    /**
     * '排除没有排班医生的科室不显示'
     * @param $date
     * @param $period '上下午'
     * @param $dept_id '科室id'
     *
     */

    public function DoctorCount($date, $period, $dept_id)
    {
        $Content = '<HIS><date>' . $date . '</date><period>' . $period . '</period><dept_id>' . $dept_id . '</dept_id></HIS>';
        $searchKey = "dutyDoctor";
        $result = $this->soapGetDate($searchKey, $Content);
        return $result;
    }


    /**
     * 值班医生列表
     * @param  $data '时间'
     * @param  $period '上午或是下午'
     * @param  $dept_id '科室id'
     *
     */
    public function dutyDoctor()
    {
//        $sign       = $this->middelEnCodeSign($_POST);
//        if($sign!=$_POST['sign']){
//            echo "签名不正确";exit;
//        }
        $date = $_POST['date'];
        $date = date('Y-m-d', strtotime($date));
//        $date = date('Y-m-d');
        $period = $_POST['period'];
        $dept_id = $_POST['deptId'];
//        $dept_id = '0011';

        $Content = '<HIS><date>' . $date . '</date><period>' . $period . '</period><dept_id>' . $dept_id . '</dept_id></HIS>';
        $searchKey = "dutyDoctor";
        $result = $this->soapGetDate($searchKey, $Content);
        //>>查询出科室名
        /*$redis = \Common\Model\ServeModel::serveRedis();
        $key = 'dept' . $dept_id;
        $dept_name = $redis->get($key);*/

        if ((int)$result['status'] == 0 && !empty($result['data'])) {

            $returnArr['status'] = 1;
            $returnArr['errorMsg'] = "";
            if (count($result['data'][0]) == 0 && $dept_id == $result['data']['dept_id']) {
                $result['data']['deptHisId'] = $dept_id;
                $result['data']['deptName'] = $dept_name;
                $result['data']['name'] = $result['data']['name'];
                $returnArr['data'][0] = $result['data']['item'];
            } else {

                foreach ($result['data'] as &$v) {
                    $v['docId'] = $v['doctor_id'];
                    $v['deptHisId'] = $v['dept_duty_id'];
                    $v['deptName'] = $dept_name;
                    $v['name'] = $v['name'];
                    $v['profession'] = '';
                    $v['rest'] = 0;
                }
                $returnArr['data'] = $result['data'];
            }

        } else {
            $returnArr['status'] = 2;
            $returnArr['errorMsg'] = '未找到此值班医生信息';
            $returnArr['data'] = array();
        }
        echo json_encode($returnArr);
    }


    /**
     * 医生查询
     * @param $data '时间'
     * @param $period '上午或是下午'
     * @param $doc_id '值班医生id'
     */
    public function getDoctorSource()
    {
//        $sign = $this->middelEnCodeSign($_POST);
//        if ($sign != $_POST['sign']) {
//            echo "签名不正确";
//            exit;
//        }
        $date1 = $_POST['date'];
//        $date1 =  date('Y-m-d');
        $date = date('Y-m-d', strtotime($date1));
        $period = $_POST['time'];
//        $period = 'pm';
        $doc_id = $_POST['docHisId'];
//        $doc_id = '0212';

        $Content = "<HIS><date>" . $date . "</date><period>" . $period . "</period><doctor_id>" . $doc_id . "</doctor_id></HIS>";
        //$Content = "<HIS><date>2017.03.29</date><period>pm</period><doctor_id>0101</doctor_id></HIS>";
        $searchKey = "doctor";
        $result = $this->soapGetDate($searchKey, $Content);
            //dump($result);
        if ($result['status'] == 0 && !empty($result['data'])) {

            $returnArr['result'] = 1;
            $returnArr['errorMsg'] = "";
            $returnArr['data']['info'] = $result['data']['info'];
            $returnArr['data']['duty'][0] = $result['data']['duty'];
            $returnArr['data']['duty'][0]['date'] = $date1;
            $returnArr['data']['duty'][0]['range'] = $period;
            $returnArr['data']['duty'][0]['treat_date'] = $date1;
            $returnArr['data']['duty'][0]['examfee'] = (int)$result['data']['duty']['examfee'];
            $returnArr['data']['duty'][0]['fee'] =  $result['data']['info']['fee'];

            if (($result['data']['duty']['total'] - $result['data']['duty']['use']) < 0) {
                $returnArr['data']['duty'][0]['rest'] = 0;
            } else {
                $returnArr['data']['duty'][0]['rest'] = $result['data']['duty']['total'] - $result['data']['duty']['use'];
            }
        } else {
            $returnArr['result'] = 2;
            $returnArr['errorMsg'] = $result['errorMsg'];
            $returnArr['data'] = array();
        }
        echo json_encode($returnArr);
    }

    /**
     * 确认挂号 (锁号)
     * @param $act '取号锁号 --类型'
     * @param $doc_id '值班医生id'
     * @param $data '时间'
     * @param $period '上午或是下午'
     * @param $fee '挂号金额'
     */
    public function registration()
    {
//        $sign = $this->middelEnCodeSign($_POST);
//        if ($sign != $_POST['sign']) {
//            echo "签名不正确";
//            exit;
//        }
        $act = $_POST['act'];
        $doc_id = $_POST['docHisId'];
        $date = $_POST['date'];
        $date = date('Y.m.d', strtotime($date));
        $period = $_POST['period'];
        $fee = $_POST['fee'];

        $Content = "<HIS><act>" . $act . "</act><doc_id>" . $doc_id . "</doc_id><day>" . $date . "</day><period>" . $period . "</period></HIS>";
        $Content = "<HIS><act>lock</act><doc_id>0109</doc_id><day>2017.03.29</day><period>am</period></HIS>";
        $searchKey = "registration";
        $result = $this->soapGetDate($searchKey, $Content);
        dump($result);

        if ($result['status'] == 0 && !empty($result['data'])) {
            $returnArr['status'] = 1;
            $returnArr['errorMsg'] = "";
            $result['data']['result'] = $result['data']['result'];
            $result['data']['fee'] = $fee;
            $returnArr['data'] = $result['data'];
        } else {
            $returnArr['status'] = 2;
            $returnArr['errorMsg'] = $result['ResultMsg'];
            $returnArr['data'] = array();
        }
        echo json_encode($returnArr);
    }

    /**
     * 挂号支付确认(取号)
     * @param $data     '时间'
     * @param $period    '上下午'
     * @param $apptid   '号源编码(锁号)'
     * @param $cardNO   '就诊卡号'
     * @param $bankNo   '交易流水号'
     * @param $fee      '挂号金额'
     */

    public function registrationFetch(){
        $sign = $this->middelEnCodeSign($_POST);
        if($sign!=$_POST['sign']){
            echo "签名不正确";exit;
        }
        $date           = $_POST['date'];
        $period1        = $_POST['period'];
        if ($period1 == 'am'){
            $period ='上午';
        }elseif($period1== 'pm'){
            $period ='下午';
        }
        $apptId     = $_POST['ApptId'];
        $cardNo     = $_POST['cardNo'];
        $bank_no    = $_POST['transaction_id'];
        $fee        = $_POST['fee'];

        $Content    ='<HIS><act>fetch</act><appt_id>'.$apptId.'</appt_id><card_no>'.$cardNo.'</card_no><bank_no>'.$bank_no.'</bank_no><pay_name>微信支付</pay_name><fee>'.$fee.'</fee></HIS>';
        $searchKey  = "registration";
        $result     = $this->soapGetDate($searchKey, $Content);

        //数组元素转换
        $year       = substr($date, 0,4);
        $month      = substr($date, 5,2);
        $day        = substr($date, 8,2);
        $data['RegYear']    = $year;
        $data['RegMonth']   = $month;
        $data['RegDay']     = $day;
        $data['date']       = $date;
        $data['date']       = $result['data']['date'];
        $data['serNo']      = $result['data']['ser_no'];
        $data['apptId']     = $result['data']['appt_id'];
        $data['patName']    = $result['data']['pat_name'];
        $data['docName']    = $result['data']['doctor_name'];
        $data['queueNo']    = $result['data']['queue_no'];
        $data['address']    = $result['data']['address'];
        $data['regType']    = $result['data']['dept_name'];
        $data['LocInfo']    = "绵阳妇幼保健院";
        $data['fee']        = $result['data']['fee'];
        $data['invoiceNo']  = $result['data']['invoice_no'];
        $data['TimeInfo']   = "请携带就诊卡于" . $year . "年" . $month . "月" . $day . " 日" .$period. "直接前往就诊科室就诊，并告知医务人员系微信挂号。如已过当天当班未就诊，医院不再安排就诊及退费";

        if ($result['status'] == 0 && !empty($result['data'])) {
            $returnArr['status']        = 1;
            $returnArr['errorMsg']      = "";
            $returnArr['data']          = $data;
        } else {
            $returnArr['status']        = 2;
            $returnArr['errorMsg']      = $result['error_msg'];
            $returnArr['data']          = array();
        }

        echo json_encode($returnArr);
    }

    /**
     *  病人就诊的医嘱信息
     * $param $cardId  '就诊卡号'
     */

    public function doctorAdvice(){
        $sign      = $this->middelEnCodeSign($_POST);
        if($sign  !=$_POST['sign']){
            echo "签名不正确";exit;
        }
        $cardId     = $_POST['cardId'];

        $Content    = "<Request><CardNo>".$cardId."</CardNo></Request>";
        $searchKey  = "Get_DoctorAdvice";
        $result     = $this->soapGetDate($searchKey, $Content);
        $data       = array();
        $i          = $totolFee = 0;
        //返回数据
        if ($result['ResultCode'] == 0) {
            $returnArr['status']            = 1;
            $returnArr['errorMsg']          = "";
            if(!is_array($result['Data']['Categories']['bill']) || count($result['Data']['Categories']['bill']) == 0) {
                $returnArr['status']        = 2;
                $returnArr['errorMsg']      = "暂无缴费数据";
                echo json_encode($returnArr);exit;
            }
            $data['payList'][0]['recipeId'] = $result['Data']['info']['advId'];

            foreach($result['Data']['Categories']['bill'] as $k1 => &$v1 ){
//                        $data['payList'][0]['type'] = $v1['cateType'];
                $data['payList'][0]['fee']  = $result['Data']['info']['feeSum'] ;

                if($v1['item'][0] != null) {
                    foreach($v1['item'] as $k => $v) {
                        $totolFee += $v['fee'];
                    }
                }else{
                    $totolFee += $v1['item']['fee'];
                }
                $i++ ;
            }


            $data['payList'][0]['orderNumber']  = $totolFee;
            $data['payList'][0]['payDate']      = date("Y-m-d");
            $returnArr['data']                  =$data;
        } else {
            $returnArr['status']     = 2;
            $returnArr['errorMsg']   = $result['ResultMsg'];
            $returnArr['data']       = array();
        }

        echo json_encode($returnArr);
    }

    /**
     * 生成缴费订单
     * @Param  $cardId  '就诊卡号'
     */

    public function preGeneratePayOrder(){
        $sign = $this->middelEnCodeSign($_POST);
        if($sign!=$_POST['sign']){
            echo "签名不正确";exit;
        }
        $cardId     = $_POST['cardId'];

        $Content    = "<Request><CardNo>".$cardId."</CardNo></Request>";
        $searchKey  = "Get_DoctorAdvice";
        $result     = $this->soapGetDate($searchKey, $Content);
        $data       =  $items = $fee_max= array();
        if ($result['ResultCode'] == 0) {
            $returnArr['status']            = 1;
            $returnArr['errorMsg']          = "";
            $categories                     = array();
            $i                              = $totolFee = 0;
            $totolFee                       = $result['Data']['info']['feeSum'];
            $categories[0]['advId']         = $result['Data']['info']['advId'];
            $categories[0]['cateName']      = $result['Data']['info']['patName'];
            $categories[0]['createDoctor']  = $result['Recipe']['DoctName'];
            $categories[0]['treat_time']    = $result['Recipe']['RecipeDate'];
            $categories[0]['cateFee']       = (float)$result['Data']['info']['feeSum'];
            $recipeList = array();
            if(isset($result['Data']['Categories']['bill'][0])){
                $recipeList = $result['Data']['Categories']['bill'];
            }else{
                $recipeList[] =$result['Data']['Categories']['bill'];
            }

            foreach ($recipeList as $k => $v) {
                //判定药品类显示详情,其他的只显示大类
                if( $v['cateName'] == "西药" || $v['cateName'] == "草药" ) {
                    if(isset($v['item'][0])) {
                        $item = $v['item'];
                    }else{
                        $item[] =$v['item'];
                    }
                    foreach ($item as $key => $value) {
                        $categories[$i]['items'] [$key]['itemName']  = $value['itemName'];
                        $categories[$i]['items'] [$key]['fee']       = substr($value['price'],0,4);
                        $categories[$i]['items'] [$key]['quantity']  = (int)$value['quantity'];;
                        $fee_max                 = $v['cateFee'];
                        $categories[$i]['items'] [$key]['address']   = $value['address'];
                        $categories[$i]['items'] [$key]['itemId']    = '';
                        $categories[$i]['items'] [$key]['unit']      = '';
                    }

                }else{
                    $categories[$i]['items'] [$k]['itemName']  = $v['cateName'];
                    $categories[$i]['items'] [$k]['fee']       = (float)$v['cateFee'];
                    $categories[$i]['items'] [$k]['quantity']  = $v['quantity'];;
                    $fee_max                 = $v['cateFee'];
                    $categories[$i]['items'] [$k]['address']   = '';
                    $categories[$i]['items'] [$k]['itemId']    = '';
                    $categories[$i]['items'] [$k]['unit']      = '';
                }
                $data['orderNumber']            = $v['No'];
                $categories[$i]['cateFee']      = $fee_max;
                $i++;
            }

            //可能存在多天的，这儿多加一层
            $data['advId']       = $result['Data']['info']['advId'];
            $data['fee']         = $totolFee;
            $data['payDate']     = date("Y-m-d");
            $data['categories']  = $categories;

            $returnArr['data']   = $data;

        } else {
            $returnArr['status']     = 2;
            $returnArr['errorMsg']   = $result['ResultMsg'];
            $returnArr['data']       = array();
        }
        echo json_encode($returnArr);
    }

    /**
     * 门诊缴费
     * @param $card_no   '就诊卡号'
     * @param $adv_id    '医嘱编号'
     * @param $fee       '缴费金额'
     * @param $bank_no   '缴费流水号'
     */
    public function outPatientPay(){
        $sign = $this->middelEnCodeSign($_POST);
        if($sign!=$_POST['sign']){
            echo "签名不正确";exit;
        }
        $card_no            = $_POST['cardNo'];
        $medicineRetrun     = $_POST['medicineRetrun'];
        $medicineRetruninfo = json_decode($medicineRetrun,true);
        $adv_id             = $medicineRetruninfo['advId'];
        $fee                = $medicineRetruninfo['fee'];
        $bank_no            =$_POST['transaction_id'];

        $Content            = "<Request><CardNo>".$card_no."</CardNo><AdvId>".$adv_id."</AdvId><Fee>".$fee."</Fee><BillNo>".$bank_no."</BillNo><PayName>微信支付</PayName></Request>";
        $searchKey          = "Exc_Pay";
        $result             = $this->soapGetDate($searchKey, $Content);

        if ($result['ResultCode']  == 0) {
            $returnArr['status']   = 1;
            $returnArr['errorMsg'] =$result['ResultMsg'];
            $returnArr['data']     = $result['Data']['item'];
        } else {
            $returnArr['status']   = 2;
            $returnArr['errorMsg'] = $result['ResultMsg'];
            $returnArr['data']     = array();
        }
        echo json_encode($returnArr);
    }


    /**
     * 查询住院病人信息
     * @param $treat_no  '住院号码'
     */

    public function getPayInfo() {
        $sign = $this->middelEnCodeSign($_POST);
        if($sign!=$_POST['sign']){
            echo "签名不正确";exit;
        }
        if($_POST['inpatientId']){
            $treat_no   = $_POST['inpatientId'];
        }else{
            $treat_no   =  $_POST['cardNo'];
        }

        $Content    = "<Request><CardNo>".$treat_no."</CardNo></Request>";
        $searchKey  = "Get_Hospitalization";
        $Result_K   = $searchKey."Result";
        $result     = $this->soapGetDate($searchKey, $Content, $Result_K);

        //>>转换数组元素
        $result['Data']['info']['cardId']           = $result['Data']['info']['cardNo'];
        $result['Data']['info']['treat_no']         = $treat_no;
        $result['Data']['info']['patient_name']     = $result['Data']['info']['patName'];
        $result['Data']['info']['dept_name']        = $result['Data']['info']['deptName'];
        $result['Data']['info']['inhospital_date']  = $result['Data']['info']['inhosptialDate'];
        $result['Data']['info']['bed_no']           = !empty($result['Data']['info']['bedNo']) ? $result['Data']['info']['bedNo'] : '未分床号';
        $result['Data']['info']['total_fee']        = (float)$result['Data']['info']['totalFee'];
        $result['Data']['info']['prepay_fee']       = (float)$result['Data']['info']['prepayFee'];
        $result['Data']['info']['arrears_fee']      = (float)$result['Data']['info']['restFee'];
        $result['Data']['info']['InpatientId']      = $treat_no;

        if ((int)$result['ResultCode']  == 0 && count($result['Data']['info'])>0) {
            $returnArr['status']   = 1;
            $returnArr['errorMsg'] = "";
            $returnArr['data']     = $result['Data']['info'];
        } else {
            $returnArr['status']   = 2;
            $returnArr['errorMsg'] = $result['ResultMsg'];
            $returnArr['data']     = array();
        }
        echo json_encode($returnArr);
    }


    /**
     *  预交费支付
     * @param $card_no    '住院号码'
     * @param $pay_fee    '住院金额'
     * @param $bank_no    '交易流水号'
     */

    public function prePayOrderSubmit(){
        $sign = $this->middelEnCodeSign($_POST);
        if($sign!=$_POST['sign']){
            echo "签名不正确";exit;
        }
        $card_no    =  $_POST['InpatientId'];
        $pay_fee    =  $_POST['fee']/100;
        $bank_no    =  $_POST['transaction_id'];

        $Content    = "<Request><CardNo>".$card_no."</CardNo><PayFee>".$pay_fee."</PayFee><BillNo>".$bank_no."</BillNo><PayName>微信支付</PayName></Request>";
        $searchKey  = "Exc_HospitalizationPay";
        $Result_K   = $searchKey."Result";
        $result     = $this->soapGetDate($searchKey, $Content, $Result_K);

        if ((int)$result['ResultCode']   == 0) {
            $returnArr['status']    = 1;
            $returnArr['errorMsg']  = "";
            $returnArr['data']      = $result['Data']['info'];
        } else {
            $returnArr['status']    = 2;
            $returnArr['errorMsg']  = $result['ResultMsg'];
            $returnArr['data']      = array();
        }
        echo json_encode($returnArr);
    }

    /**
     * 预交费生成订单
     * @param  $treat_no  '住院号码'
     */

    public function createPayOrder(){
        $sign = $this->middelEnCodeSign($_POST);
        if($sign!=$_POST['sign']){
            echo "签名不正确";exit;
        }
        $treat_no   =  $_POST['inpatientId'];

        $Content    = "<Request><CardNo>".$treat_no."</CardNo></Request>";
        $searchKey  = "Get_Hospitalization";
        $Result_K   = $searchKey."Result";
        $result     = $this->soapGetDate($searchKey, $Content, $Result_K);

        //>>转换数组元素
        $result['Data']['info']['treat_no']         = $result['Data']['info']['treatNo'];
        $result['Data']['info']['patient_name']     = $result['Data']['info']['patName'];
        $result['Data']['info']['dept_name']        = $result['Data']['info']['deptName'];
        $result['Data']['info']['inhospital_date']  = substr($result['Data']['info']['inhosptialDate'],0,9);
        $result['Data']['info']['bed_no']           = !empty($result['Data']['info']['bedNo']) ? $result['Data']['info']['bedNo'] : '未分床号';
        $result['Data']['info']['total_fee']        =(float) $result['Data']['info']['totalFee'];
        $result['Data']['info']['prepay_fee']       = (float)$result['Data']['info']['prepayFee'];
        $result['Data']['info']['arrears_fee']      = (float)$result['Data']['info']['restFee'];

        if ((int)$result['ResultCode']  == 0) {
            $returnArr['status']   = 1;
            $returnArr['errorMsg'] = "";
            $returnArr['data']     = $result['Data']['info'];
        } else {
            $returnArr['status']   = 2;
            $returnArr['errorMsg'] = $result['ResultMsg'];
            $returnArr['data']     = array();
        }
        echo json_encode($returnArr);
    }


    //检查是否可以支付 默认通过
    public function checkOrder(){
        $returnArr['status'] = 1;
        echo json_encode($returnArr);
    }

    /**
     *  住院缴费清单 (住院号码)
     * @param  $inpatientId  '住院号码'
     * @param  $start_ts     '开始时间'
     * @param  $end_ts       '结束时间'
     */
    public function prePayOrderList(){
        $sign = $this->middelEnCodeSign($_POST);
        if($sign!=$_POST['sign']){
            echo "签名不正确";exit;
        }
        $inpatientId    = $_POST['inpatientId'];
        $start_ts       = $_POST['start_ts'];

        $Content        = "<Request><CardNo>".$inpatientId."</CardNo><Startdate>".$start_ts."</Startdate><Enddate>".$start_ts."</Enddate></Request>";
        $searchKey      = "Get_ChargeOfIn";
        $Result_K       = $searchKey."Result";
        $result         = $this->soapGetDate($searchKey, $Content, $Result_K);
        $data           = $res =array();
        $i              = 0 ;
        //>>数组元素转换

        foreach($result['Data']['Item'] as $key=>$val) {
//                    $data['Item'][$i]['ItemType']       = $v['FeeName'];
            $data['Item'][$i]['OperDateTime']   = substr($val['BuinessDate'],0,-7);
            $data['Item'][$i]['ItemName']       = $val['ItemName'];
            $data['Item'][$i]['DeptName']       = $val['DepartName'];
            $data['Item'][$i]['Specs']          = !empty($val['Specs']) ? $val['Specs'] : '';
            $data['Item'][$i]['Unit']           = $val['Unit'];
            $data['Item'][$i]['Price']          = (float)$val['Price'];
            $data['Item'][$i]['Num']            = $val['Nums'];
            $data['Item'][$i]['Cost']           = (float)$val['Cost'];
            $i ++ ;
        }

        if ((int)$result['ResultCode'] == 0) {
            $returnArr['status']    = 1;
            $returnArr['errorMsg']  = $result['ResultMsg'];
            $returnArr['data']      = $data['Item'];
        } else {
            $returnArr['status']    = 2;
            $returnArr['errorMsg']  = $result['ResultMsg'];
            $returnArr['data']      = array();
        }
        echo json_encode($returnArr);
    }

    /**
     *  [门诊费用清单](就诊卡号)
     * @param  $inpatientId  '就诊号码'
     * @param  $start_ts     '开始时间'
     * @param  $end_ts       '结束时间'
     */
    public function prePayDoorList(){
        $sign = $this->middelEnCodeSign($_POST);
        if($sign!=$_POST['sign']){
            echo "签名不正确";exit;
        }
        $inpatientId    = $_POST['inpatientId'];
        $start_ts       = $_POST['start_ts'];
        $end_ts         = $_POST['end_ts'];

        $Content        = "<Request><CardNo>".$inpatientId."</CardNo><Startdate>".$start_ts."</Startdate><Enddate>".$end_ts."</Enddate></Request>";
        $searchKey      = "Get_Recipe_Detail";
        $Result_K       = $searchKey."Result";
        $result         = $this->soapGetDate($searchKey, $Content, $Result_K);
        $data           = array();
        $i              = 0 ;
        //>>数组元素转换

        if(count($result['Data']['FeeType'][0])== 0 ){
            $result['Data']['FeeType'][0]   = $result['Data']['FeeType'];
        }

        foreach($result['Data']['FeeType'] as $k =>&$v) {
            $data['Total']   += $v['Total'];
            if(count($v['Items']['Item']['ItemCode']) == 1){
                $data['Item'][0]['ItemType']       = $v['FeeName'];
                if($v['Items']['Item']['ItemName'] == null) {
                    $data['Item'][0]['ItemName']       = $v['FeeName'];
                }else{
                    $data['Item'][0]['ItemName']       = $v['Items']['Item']['ItemName'];
                }

                $data['Item'][0]['Specs']          = $v['Items']['Item']['Specs'];
                if($v['Items']['Item']['Unit'] == null) {
                    $data['Item'][0]['Unit']       = '';
                }else{
                    $data['Item'][0]['Unit']       = $v['Items']['Item']['Unit'];
                }
                $data['Item'][0]['Price']          = $v['Items']['Item']['Price'];
                $data['Item'][0]['Num']            = (int)$v['Items']['Item']['Nums'];
                $data['Item'][0]['Cost']           = $v['Items']['Item']['Cost'];
            }else{
                foreach($v['Items']['Item'] as $val) {

                    $data['Item'][$i]['ItemType']       = $v['FeeName'];
                    if($val['ItemName'] == null ) {
                        $data['Item'][$i]['ItemName']   = $v['FeeName'];
                    }else{
                        $data['Item'][$i]['ItemName']   = $val['ItemName'];
                    }
                    $data['Item'][$i]['Specs']          = $val['Specs'];
                    if($val['Unit'] == null ) {
                        $data['Item'][$i]['Unit']       ='';
                    }else{
                        $data['Item'][$i]['Unit']       = $val['Unit'];
                    }
                    $data['Item'][$i]['Price']          = $val['Price'];
                    $data['Item'][$i]['Num']            = (int)$val['Nums'];
                    $data['Item'][$i]['Cost']           = $val['Cost'];
                    $i++;
                }
            }

        }
        if ((int)$result['ResultCode'] == 0) {
            $returnArr['status']    = 1;
            $returnArr['errorMsg']  = $result['ResultMsg'];
            $returnArr['data']      = $data;
        } else {
            $returnArr['status']    = 2;
            $returnArr['errorMsg']  = $result['ResultMsg'];
            $returnArr['data']      = array();
        }
        echo json_encode($returnArr);
    }

    /**
     *  住院交款记录(住院号码)
     * @param  $inpatientId  '住院号码'
     * @param  $start_ts     '开始时间'
     * @param  $end_ts       '结束时间'
     */
    public function prePayMentList(){
        $sign = $this->middelEnCodeSign($_POST);
        if($sign!=$_POST['sign']){
            echo "签名不正确";exit;
        }
        $inpatientId    = $_POST['inpatientId'];

        $Content        = "<Request><CardNo>".$inpatientId."</CardNo></Request>";
        $searchKey      = "Get_Fee_Bill";
        $Result_K       = $searchKey."Result";
        $result         = $this->soapGetDate($searchKey, $Content, $Result_K);

        if( count($result['Data']['Items'][0]) == 0 ) {
            $result['Data']['Items'][0] = $result['Data']['Items'];
        }
        if ($result['ResultCode'] == 0) {
            $returnArr['status']    = 1;
            $returnArr['errorMsg']  = $result['ResultMsg'];
            $returnArr['data']      = $result['Data'];
        } else {
            $returnArr['status']    = 2;
            $returnArr['errorMsg']  = '暂无交款记录';
            $returnArr['data']      = array();
        }
        echo json_encode($returnArr);

    }

    // TODO: 停诊通知
    public function doctorStopWorke(){
        $data['date'] = date('Y-m-d');
        $searchKey = '/notify';
        $params = array();
        $params['reqData'] = json_encode($data);
        $r = $this->Post(self::$URL_API.$searchKey,__FUNCTION__,$params);
        $result = json_decode($r,true);
        dump($result);
        if(isset($result['data'])){
            $stopList = array();
            //处理单条数据
            if(isset($result['data'][0])){
                $stopList = $result['data'];
            }else{
                $stopList[0] = $result['data'];
            }
            foreach($result['data'] as $v){
                //
            }
        }
    }

    /**
     * 检查报告列表
     *
     */

    public function myInspectReport(){

        $sign = $this->middelEnCodeSign($_POST);
        if($sign!=$_POST['sign']){
            echo "签名不正确";exit;
        }

        $inpatientId = $_POST['cardNo'];
        $start_ts    = date('Y-01-01',strtotime("-1 year"));
        $end_ts      = date('Y-m-d');

        $Content     = "<Request><CardNo>".$inpatientId."</CardNo><Startdate>".$start_ts."</Startdate><EndDate>".$end_ts."</EndDate></Request>";
        $searchKey   = "Get_Pacs_List";
        $Result_K    = $searchKey."Result";
        $result      = $this->soapGetDate($searchKey, $Content, $Result_K);
        //数组元素转换
        $params      =  $it_name = array();
        if(!isset($result['Data']['item'][0])){
            $params[0]  = $result['Data']['item'];
        }else{
            $params     = $result['Data']['item'];
        }
        foreach($params as &$v){

            $v['item_name']     = $v['checkName'];
            $v['report_date']   = $v['checkTime'];
            $v['inspec_no']     = $v['checkId'];
            $v['archive_date']  = $v['checkTime'];
            $v['inspect_id']    = $v['checkId'];
        }
        $data = array();
        foreach($params as &$vv){
            if(substr($vv['checkTime'],0,7) == date('Y-m')){
                $data['currentMonth'][]     = $vv;
            }else{
                $data['preMonth'][]         = $vv;
            }
        }
        if ($result['ResultCode'] == 0) {
            $returnArr['status']      = 1;
            $returnArr['errorMsg']    = $result['ResultMsg'];
            $returnArr['data']        = $data;
        } else {
            $returnArr['status']      = 1;
            $returnArr['errorMsg']    = $result['ResultMsg'];
            $returnArr['data']        = array();
        }
        echo json_encode($returnArr);

    }

//    /**
//     * 检查报告结果
//     * @param   $inspectId   '(检验报告列表)返回inspectId节点'
//     */
//    public function myInspectReportResult(){
//        $sign = $this->middelEnCodeSign($_POST);
//        if($sign!=$_POST['sign']){
//            echo "签名不正确";exit;
//        }
//        $inspectId  = $_POST['inspec_no'];
//        $CardNo     = $_POST['cardNo'];
//
//        $Content    = "<Request><CardNo>".$CardNo."</CardNo><InspectId>".$inspectId."</InspectId></Request>";
//        $searchKey  = "Get_Pacs_Result";
//        $Result_K   = $searchKey."Result";
//        $result     = $this->soapGetDate($searchKey, $Content, $Result_K);
//
//        if ( $result['ResultCode'] == 0) {
//            $returnArr['status'] = 1;
//            $returnArr['errorMsg'] = $result['ResultMsg'];
//
//            $itemInfo = $result['Data'];
//            $returnArr['data']['type'] = 3;
//            $returnArr['data']['exam_type'] = $itemInfo['Exam_RptSee'];
//            $returnArr['data']['exam_item'] = $itemInfo['Conclusion'];
//            $returnArr['data']['exam_no']   = $itemInfo['InspectId'];
//            $returnArr['data']['exam_desp'] = !empty(trim($itemInfo['Exam_RptSugg']))?trim($itemInfo['Exam_RptSugg']):"暂无";
//            $returnArr['data']['diagno_result'] =!empty(trim($itemInfo['Exam_RptDiag'])) ?trim($itemInfo['Exam_RptDiag']):"暂无";
//            $returnArr['data']['diagno_date'] = $itemInfo['ReportDate'];
//        } else {
//            $returnArr['status'] = 2;
//            $returnArr['errorMsg'] = "暂未获取到电子报告结果,请到现场获取报告";
//            $returnArr['data'] = array();
//        }
//
//        echo json_encode($returnArr);
//        exit;
//    }


    /**
     * 检验报告列表
     * @param  $inpatientId  '就诊号码'
     * @param  $start_ts     '开始时间'
     * @param  $end_ts       '结束时间'
     */
    public function myExamineReport(){
        $sign = $this->middelEnCodeSign($_POST);
        if($sign!=$_POST['sign']){
            echo "签名不正确";exit;
        }

        $inpatientId = $_POST['cardNo'];
        $start_ts    = date('Y-01-01',strtotime("-1 year"));
        $end_ts      = date('Y-m-d');

        $Content     = "<Request><CardNo>".$inpatientId."</CardNo><beginDate>".$start_ts."</beginDate><endDate>".$end_ts."</endDate></Request>";
        $searchKey   = "Get_Lis_List";
        $Result_K    = $searchKey."Result";
        $result      = $this->soapGetDate($searchKey, $Content, $Result_K);
        //数组元素转换
        $params      =  $it_name = array();
        if(!isset($result['Data']['item'][0])){
            $params[0]  = $result['Data']['item'];
        }else{
            $params     = $result['Data']['item'];
        }
        foreach($params as &$v){

            $v['item_name']     = $v['inspectName'];
            $v['report_date']   = $v['reportTime'];
            $v['inspec_no']     = $v['inspectStatus'];
            $v['archive_date']  = $v['reportTime'];
            $v['inspect_id']    = $v['inspectId'];
        }
        $data = array();
        foreach($params as &$vv){
            if(substr($vv['reportTime'],0,7) == date('Y-m')){
                $data['currentMonth'][]     = $vv;
            }else{
                $data['preMonth'][]         = $vv;
            }
        }
        if ($result['ResultCode'] == 0) {
            $returnArr['status']      = 1;
            $returnArr['errorMsg']    = $result['ResultMsg'];
            $returnArr['data']        = $data;
        } else {
            $returnArr['status']      = 1;
            $returnArr['errorMsg']    = $result['ResultMsg'];
            $returnArr['data']        = array();
        }
        echo json_encode($returnArr);
    }


    /**
     * 检验报告结果
     * @param   $inspectId   '(检验报告列表)返回inspectId节点'
     */
    public function myExamineReportResult(){
        $sign = $this->middelEnCodeSign($_POST);
        if($sign!=$_POST['sign']){
            echo "签名不正确";exit;
        }
        $inspectId  = $_POST['inspectId'];
        $CardNo     = $_POST['cardNo'];

        $Content    = "<Request><CardNo>".$CardNo."</CardNo><inspectId>".$inspectId."</inspectId></Request>";
        $searchKey  = "Get_Lis_Result";
        $Result_K   = $searchKey."Result";
        $result     = $this->soapGetDate($searchKey, $Content, $Result_K);

        //数组元素转换
        $result['user_name']    = $result['Data']['patientName'];
        $result['sex']          = $result['Data']['patientSex'];
        $result['age']          = $result['Data']['patientAge'];
        $result['pid']          = $result['Data']['cardNo'];
        $result['sample_name']  = $result['Data']['inspectName'];
        $result['section']      = $result['Data']['deptName'];
        $params                 = array();
        if(!isset($result['Data']['item'][0])){
            $params[0]  = $result['Data']['item'];
        }else{
            $params     = $result['Data']['item'];
        }
        foreach($params as &$v){
            $v['item_name']     = $v['itemName'];
            $v['exam_value']    = $v['result'];
            if($v['abnormal'] == 0) {
                $v['abnormal']  = "正常" ;
            }elseif($v['abnormal'] == 1) {
                $v['abnormal']  = "偏高" ;
            }elseif($v['abnormal'] == 2){
                $v['abnormal']  = "偏低" ;
            }
            $v['result_state']  = !empty($v['abnormal']) ? $v['abnormal'] : '';

            $v['unit']          = !empty($v['unit']) ? $v['unit'] : '无';
            $v['ref_range']     = !empty($v['refRange']) ? $v['refRange'] : '无';
        }
        $data                   = array();
        $data['status']         = 1;
        $data['errorMsg']       = $result['ResultMsg'];

        if($result['ResultCode'] != 0){
            $data['status']     = 2;
            $data['errorMsg']   = $result['ResultMsg'];
            echo json_encode($data);
            exit;
        }
        $data['data']           = $result;
        $data['data_list']      = $params;
        echo json_encode($data);
        exit;
    }

    /**
     * 取消挂号
     * @param  $invoiceNo   '(取号)返回的invoiceNo节点'
     */
    function cancelReg(){
        $sign = $this->middelEnCodeSign($_POST);
        if($sign!=$_POST['sign']){
            echo "签名不正确";exit;
        }
        $invoiceNo  = $_POST['invoiceNo'];

        $Content    = "<Request><VisitNO>".$invoiceNo."</VisitNO></Request>";
        $searchKey  = "Cancel_Reg";
        $Result_K   = $searchKey."Result";
        $result     = $this->soapGetDate($searchKey, $Content, $Result_K);

        if ($result['ResultCode'] == 0 ) {
            $returnArr['status']    = 1;
            $returnArr['errorMsg']  = $result['ResultMsg'];
            $returnArr['data']      = $result;
        } else {
            $returnArr['status']    = 2;
            $returnArr['errorMsg']  = $result['ResultMsg'];
            $returnArr['data']      = $result;
        }
        echo json_encode($returnArr);
        exit;
    }
    /**
     * 对账
     * @param  data '请求参数his用处不大'
     */
    public function BalanceToWeixin(){
//        $sign = $this->middelEnCodeSign($_POST);
//        if($sign!=$_POST['sign']){
//            echo "签名不正确";exit;
//        }
        $date       = date('Y-m-d');

        $Content    = "<Request><Date>".$date."</Date></Request>";
        $searchKey  = "Get_Trade_List";
        $Result_K   = $searchKey."Result";
        $result     = $this->soapGetDate($searchKey, $Content, $Result_K);
        //数组元素转换
        $params = array();
        if(is_array($result['Data']['item']) && !isset($result['Data']['item'][0])){
            $params[0] = $result['Data']['item'];
        }else{
            $params     = $result['Data']['item'];
        }
        foreach($params as &$v){
            $v['transaction_id'] = $v['bankNo'];
            $v['TradeType']      = $v['tradeType'];
        }

        if ($result['ResultCode'] == 0) {
            $returnArr['status']    = 1;
            $returnArr['errorMsg']  = "";
            $returnArr['data']      = $params;
        } else {
            $returnArr['status']    = 2;
            $returnArr['errorMsg']  = $result['ResultMsg'];
            $returnArr['data']      = array();
        }
        echo json_encode($returnArr);
        exit;
    }
    /**
     * 根据订单号查询是否成功
     * @param  bankNo       '微信订单号'
     * @param  treadType    '类型'
     */
    public function GetTradResultByTradId(){
        $sign = $this->middelEnCodeSign($_POST);
        if($sign!=$_POST['sign']){
            echo "签名不正确";exit;
        }
        $transaction_id = $_POST['transaction_id'];
        $type           = $_POST['type'];
        $Content        = '<Request><bankNo>'.$transaction_id.'</bankNo><tradeType>'.$type.'</tradeType></Request>';
        $searchKey      = "Check_Exist_Bill";
        $Result_K       = $searchKey."Result";
        $result         = $this->soapGetDate($searchKey, $Content, $Result_K);
        if ($result['ResultCode'] == 0) {
            $returnArr['status']   = 1;
            $returnArr['errorMsg'] = "";
            $returnArr['data']     = $result['Data'];
        } else {
            $returnArr['status']   = 2;
            $returnArr['errorMsg'] = $result['ResultMsg'];
            $returnArr['data']     = array();
        }
        echo json_encode($returnArr);
    }



}
?>